'use strict'

const xlsx = require('xlsx');
const moment = require('moment');
const { TaiSpider } = require('tai-spider');

const ucsMapper = Object.freeze({
    "Name of Satellite, Alternate Names": "aliasName",
    "Current Official Name of Satellite": "officialName",
    "Country/Org of UN Registry": "country",
    "Country of Operator/Owner": "ownerCountry",
    "Operator/Owner": "owner",
    "Users": "users",
    "Purpose": "purpose",
    "Detailed Purpose": "detailedPurpose",
    "Class of Orbit": "orbit",
    "Type of Orbit": "orbitType",
    "Longitude of GEO (degrees)": "longitude",
    "Perigee (km)": "perigee",
    "Apogee (km)": "apogee",
    "Eccentricity": "eccentricity",
    "Inclination (degrees)": "inclination",
    "Period (minutes)": "period",
    "Launch Mass (kg.)": "launchMass",
    "Dry Mass (kg.)": "dryMass",
    "Power (watts)": "power",
    "Date of Launch": "launchDate",
    "Expected Lifetime (yrs.)": "lifetime",
    "Contractor": "contractor",
    "Country of Contractor": "contractorCountry",
    "Launch Site": "launchSite",
    "Launch Vehicle": "launchVehicle",
    "COSPAR Number": "cospar",
    "NORAD Number": "norad",
    "Comments": "comments",
    "Source Used for Orbital Data": "sourceForOribit",
    "Source": "source",
    "Source_1": "source",
});

const mapper = (json, map) => {
    return json.map(item => {
        let obj = {};
        Object.keys(item).forEach(key => {
            if (map[key]) {
                if (obj[map[key]]) {
                    if (typeof obj[map[key]] === 'array')
                        obj[map[key]].push(item[key]);
                    else
                        obj[map[key]] = [obj[map[key]], item[key]];
                } else {
                    obj[map[key]] = item[key];
                }
            }
        })
        return obj;
    })
}

const changeDate = (timeNum) => {
    const d = timeNum - 1;
    const t = Math.round((d - Math.floor(d)) * 24 * 60 * 60);
    return moment(new Date(1900, 0, d, 0, 0, t)).format('YYYY-MM-DD');
}

class UcsusaSpider extends TaiSpider {

    constructor(options = {}) {
        super(options);
        this.name = 'ucsusa';
        this.debug = true;
    }

    start_urls() {
        return [{
            link: 'https://www.ucsusa.org/media/11492',
            // download: true,
            options: {
                type: 'xls',
            },
            // http2: true,
        }]
    }

    *parse(response) {
        const workbook = xlsx.read(response.body);
        let sheetNames = workbook.SheetNames;
        let sheet = workbook.Sheets[sheetNames[0]];
        let json = xlsx.utils.sheet_to_json(sheet);

        json.forEach(item => {
            item['Date of Launch'] = changeDate(item['Date of Launch']);
        })

        // yield {
        //     index_name: 'tai-file',
        //     name: 'ucsusa'
        // }
        for (let item of mapper(json, ucsMapper)) {
            if (item.cospar) {
                yield {
                    index_name: 'tai-ucsusa',
                    id: `${item['cospar']}-${item['norad']}`,
                    ...item
                }
            }
        }
    }
}

module.exports = UcsusaSpider;